import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/views/Dashboard.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/schedule',
    name: 'Schedule',
    component: () => import('@/views/schedule/Index.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/calendar',
    name: 'Calendar',
    component: () => import('@/views/Calendar.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/master',
    name: 'Master',
    component: () => import('@/views/master/Index.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: 'teacher',
        name: 'Teacher',
        component: () => import('@/views/master/Teacher.vue')
      },
      {
        path: 'course',
        name: 'Course',
        component: () => import('@/views/master/Course.vue')
      },
      {
        path: 'class',
        name: 'Class',
        component: () => import('@/views/master/Class.vue')
      },
      {
        path: 'venue',
        name: 'Venue',
        component: () => import('@/views/master/Venue.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  if (to.meta.requiresAuth && !userStore.token) {
    next('/login')
  } else if (to.path === '/login' && userStore.token) {
    next('/dashboard')
  } else {
    next()
  }
})

export default router